package com.electric.common;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;
import java.util.regex.Matcher;

import javax.servlet.http.HttpServletRequest;

import sun.misc.BASE64Encoder;

public class CommonStringUtils {
	/**
	 * 通过request对象获取IP地址
	 * 
	 * @param request
	 * @return
	 */
	public static String getIpAddress(HttpServletRequest request) {
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("HTTP_CLIENT_IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("HTTP_X_FORWARDED_FOR");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		return ip;
	}

	/**
	 * 获取UUID
	 * 
	 * @return
	 */
	public static String getUUID() {
		return UUID.randomUUID().toString().replaceAll("-", "");
	}

	/**
	 * MD5加密
	 * 
	 * @param str
	 * @return
	 * @throws NoSuchAlgorithmException
	 * @throws UnsupportedEncodingException
	 */
	public static String md5(String str) throws NoSuchAlgorithmException, UnsupportedEncodingException {
		MessageDigest md5 = MessageDigest.getInstance("MD5");
		BASE64Encoder base64en = new BASE64Encoder();
		// 加密后的字符串
		String newstr = base64en.encode(md5.digest(str.getBytes("utf-8")));
		return newstr;
	}

	/**
	 * 根据request对象获取basePath
	 * @param request
	 * @return
	 */
	public static String getBasePath(HttpServletRequest request) {
		String basePath = request.getScheme() + "://" + request.getServerName()
				+ (request.getServerPort() == 80 ? "" : ":" + request.getServerPort()) + request.getContextPath();

		return basePath;
	}
	
	/**
	 * 校验手机号格式
	 * @param phoneStr
	 * @return
	 */
	public static boolean validatePhone(String phoneStr){
		Matcher matcher = Contains.phonePattern.matcher(phoneStr);
		return matcher.matches();
	}
	
	public static String dayFmt2MysqlFmt(String dayFmt) {
		if(Contains.DAY_FMT.equals(dayFmt)) {
			return Contains.DAY_FMT_MYSQL;
		}
		else if(Contains.MONTH_FMT.equals(dayFmt)) {
			return Contains.MONTH_FMT_MYSQL;
		}
		else if(Contains.YEAR_FMT.equals(dayFmt)) {
			return Contains.YEAR_FMT_MYSQL;
		}
		return null;
	}
}
